var labelType, useGradients, nativeTextSupport, animate;

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();

var Log = {
  elem: false,
  write: function(text){
    if (!this.elem) 
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};

var nodeWidth = 80;

function init(){
    //init data
    var json = {
        id: "node02",
        name: "目标<br />会员注册",
        data: {url: "baidu.com",name: "百度"},
        children: [{
            id: "node13",
            name: "效果联盟/<b>亿起发</b><br />100",
            data: {},
            children: [{
                id: "node24",
                name: "SNS营销/新浪微博<br />20",
                data: {},
                children: []
            }, {
                id: "node222",
                name: "效果联盟/亿起发<br />80",
                data: {},
                children: [{
                    id: "node323",
                    name: "效果联盟/亿起发<br />80",
                    data: {},
                    children: []
                }]
            }]
        }, {
            id: "node125",
            name: "自然搜索/百度/团购<br />80",
            data: {},
            children: [{
                id: "node226",
                name: "引荐网站/ tieba.baidu.com<br />80",
                data: {},
                children: []
            }]
        }, {
            id: "node165",
            name: "直接进入<br />60",
            data: {},
            children: [{
                id: "node266",
                name: "付费搜索/团购<br />30",
                data: {},
                children: []
            }, {
                id: "node283",
                name: "广告网络/亿告<br />20",
                data: {},
                children: [{
                    id: "node384",
                    name: "EDM<br />20",
                    data: {},
                    children: []
                }]
            }, {
                id: "node2104",
                name: "效果联盟/亿起发<br />10",
                data: {},
                children: []
            }]
        }]
    };
    //end
    //init Spacetree
    //Create a new ST instance
    var st = new $jit.ST({
        //id of viz container element
        injectInto: 'infovis',
        //set duration for the animation
        duration: 800,
        //set animation transition type
        transition: $jit.Trans.Quart.easeInOut,
		constrained: true,
		levelsToShow: 10,
        //set distance between node and its children
        levelDistance: 70,
        //enable panning
        Navigation: {
		  zooming: 30,
          enable: true,
          panning: true // false, true, 'avoid nodes'  
        },

		Tips : {  
		  enable: true,
		  //Possible values are ‘Native’ to attach them to the canvas or ‘HTML’ to attach them to DOM label elements (if defined).
		  type: 'auto',
		  onShow: function(tip, node) {  
		    tip.innerHTML = '<span style="font-size: 12px;">' + node.name + '</span>';  
		  }  
		},
		
        //set node and edge styles
        //set overridable=true for styling individual
        //nodes or edges
        Node: {
            height: 40,
            width: nodeWidth,
			//autoHeight: true,
			//autoWidth: true,  
			//Node types implemented are none, circle , rectangle, ellipse and square.
            type: 'rectangle',
			//背景色
            color: '#ccffcc',
			align: "center", 
            overridable: true
        },

		// Determine whether or not general label properties can be overridden by a particular Graph.Node.
//		Label: {  
//		  overridable: true,  
//		  type: 'HTML', // HTML, 'SVG', 'Native'  
//		  style: '',  
//		  size: 12,  
//		  family: 'sans-serif',  
//		  textAlign: 'center',  
//		  textBaseline: 'alphabetic',  
//		  color: '#fff'  
//		},
        
        Edge: {
			//Edge types implemented are none, line, arrow, quadratic:begin, quadratic:end, bezier.
            type: 'bezier',
            overridable: true
        },
        
        onBeforeCompute: function(node){
            Log.write("加载 " + node.name);
        },
        
        onAfterCompute: function(){
            Log.write("加载完成");
        },
        
        //This method is called on DOM label creation.
        //Use this method to add event handlers and styles to
        //your node.
        onCreateLabel: function(label, node){
            label.id = node.id;            
            label.innerHTML = node.name;
            label.onclick = function(){
				//alert(node.data.url);
//            	if(normal.checked) {
            	  st.onClick(node.id);
//            	} else {
//                  st.setRoot(node.id, 'animate');
//            	}

				//st.refresh();
            };
            //set label styles
            var style = label.style;
            style.width = nodeWidth + 'px';
            style.height = 40 + 'px';            
            style.cursor = 'pointer';
            style.color = '#333';
            style.fontSize = '12px';
            style.textAlign= 'center';
			style.textOverflow= 'ellipsis';
			//style.verticalAlign = 'middle';
			//style.overflow ='hidden';

            //style.paddingTop  = '8px';
			//style.paddingLeft = '12px';
        },
        
        //This method is called right before plotting
        //a node. It's useful for changing an individual node
        //style properties before plotting it.
        //The data properties prefixed with a dollar
        //sign will override the global node style properties.
        onBeforePlotNode: function(node){
            //add some color to the nodes in the path between the
            //root node and the selected node.
            if (node.selected) {
                node.data.$color = "#ff7";
            }
            else {
                delete node.data.$color;
                //if the node belongs to the last plotted level
                if(!node.anySubnode("exist")) {
                    //count children number
                    var count = 0;
                    node.eachSubnode(function(n) { count++; });
                    //assign a node color based on
                    //how many children it has
                    //node.data.$color = ['#aaa', '#baa', '#caa', '#daa', '#eaa', '#faa'][count];                    
                }
            }
        },
        
        //This method is called right before plotting
        //an edge. It's useful for changing an individual edge
        //style properties before plotting it.
        //Edge data proprties prefixed with a dollar sign will
        //override the Edge global style properties.
        onBeforePlotLine: function(adj){
            if (adj.nodeFrom.selected && adj.nodeTo.selected) {
                adj.data.$color = "#ffcc66";
                adj.data.$lineWidth = 3;
            }
            else {
                delete adj.data.$color;
                delete adj.data.$lineWidth;
            }
        }
    });
    //load json data
    st.loadJSON(json);
    //compute node positions and layout
    st.compute();
    //optional: make a translation of the tree
    st.geom.translate(new $jit.Complex(-200, 0), "current");
    //emulate a click on the root node.
    st.onClick(st.root);
    //end
    //Add event handlers to switch spacetree orientation.
//    var top = $jit.id('r-top'), 
//        left = $jit.id('r-left'), 
//        bottom = $jit.id('r-bottom'), 
//        right = $jit.id('r-right'),
//        normal = $jit.id('s-normal');
//        
//    
//    function changeHandler() {
//        if(this.checked) {
//            top.disabled = bottom.disabled = right.disabled = left.disabled = true;
//            st.switchPosition(this.value, "animate", {
//                onComplete: function(){
//                    top.disabled = bottom.disabled = right.disabled = left.disabled = false;
//                }
//            });
//        }
//    };
//    
//    top.onchange = left.onchange = bottom.onchange = right.onchange = changeHandler;
    //end

}
